<template>
  <div id="appChatPage">
    <!-- 顶部栏 -->
    <div class="topbar">
      <div class="left">{{ appTitle || '应用对话' }}</div>
      <div class="right">
        <a-space>
          <a-button @click="goPreview" :disabled="!previewUrl">预览</a-button>
          <a-button type="primary" :loading="deploying" @click="doDeploy">部署</a-button>
        </a-space>
      </div>
    </div>

    <!-- 核心区域：左对话 / 右预览 -->
    <div class="core">
      <div class="chat">
        <div class="messages" ref="msgRef">
          <div v-for="m in messages" :key="m.id" class="msg" :class="m.role">
            <div class="bubble">
              <div v-if="m.role === 'ai'" v-html="renderMarkdown(m.content)" class="markdown-content"></div>
              <div v-else>{{ m.content }}</div>
            </div>
          </div>
        </div>
        <div class="input">
          <a-textarea v-model:value="input" :auto-size="{ minRows: 3, maxRows: 6 }" placeholder="描述你要生成的页面或功能…" />
          <div class="input-actions">
            <a-button type="primary" :loading="sending" @click="send">发送</a-button>
          </div>
        </div>
      </div>
      <div class="preview">
        <div v-if="!previewUrl" class="placeholder">等待生成完成后展示网页预览</div>
        <iframe v-else :src="previewUrl" class="frame" />
      </div>
    </div>

    <!-- 部署成功弹窗 -->
    <a-modal
      v-model:open="deployModalVisible"
      title="部署成功"
      :footer="null"
      :width="480"
      centered
    >
      <div class="deploy-success">
        <div class="success-icon">
          <a-icon type="check-circle" style="font-size: 64px; color: #52c41a;" />
        </div>
        <div class="success-title">网站部署成功!</div>
        <div class="success-desc">你的网站已经成功部署，可以通过以下链接访问：</div>
        <div class="url-container">
          <a-input 
            :value="deployUrl" 
            readonly 
            class="url-input"
          />
          <a-button 
            type="text" 
            @click="copyDeployUrl"
            class="copy-btn"
          >
            <template #icon>
              <a-icon type="copy" />
            </template>
          </a-button>
        </div>
        <div class="action-buttons">
          <a-button type="primary" @click="visitDeployUrl" class="visit-btn">
            访问网站
          </a-button>
          <a-button @click="deployModalVisible = false">
            关闭
          </a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { chatToGenCode, deployApp, getAppById } from '@/api/appController.ts'
import { message } from 'ant-design-vue'
// @ts-ignore
import { marked } from 'marked'
// @ts-ignore
import hljs from 'highlight.js/lib/core'
// @ts-ignore
import javascript from 'highlight.js/lib/languages/javascript'
// @ts-ignore
import html from 'highlight.js/lib/languages/xml'
// @ts-ignore
import css from 'highlight.js/lib/languages/css'
// @ts-ignore
import 'highlight.js/styles/github.css'

// 注册语言
hljs.registerLanguage('javascript', javascript)
hljs.registerLanguage('html', html)
hljs.registerLanguage('css', css)

const route = useRoute()
const appId = String(route.params.id || '')

const appTitle = ref('')
const previewUrl = ref('')
const deploying = ref(false)
const sending = ref(false)
const deployModalVisible = ref(false)
const deployUrl = ref('')

type Msg = { id: string; role: 'user' | 'ai'; content: string }
const messages = reactive<Msg[]>([])
const input = ref('')
const msgRef = ref<HTMLElement>()

// 配置 marked 和代码高亮
marked.setOptions({
  highlight: function(code: string, lang: string) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(code, { language: lang }).value
      } catch (err) {
        console.error('代码高亮错误:', err)
        return code
      }
    }
    return hljs.highlightAuto(code).value
  },
  breaks: true,
  gfm: true
} as any)

// 渲染 Markdown
const renderMarkdown = (content: string) => {
  if (!content) return ''
  return marked(content)
}

const scrollToBottom = async () => {
  await nextTick()
  if (msgRef.value) {
    msgRef.value.scrollTo({ 
      top: msgRef.value.scrollHeight, 
      behavior: 'smooth' 
    })
  }
}

const init = async () => {
  const res = await getAppById({ id: appId as any })
  if (res.data.data) {
    appTitle.value = (res.data.data as any).appName ?? ''
    if ((res.data.data as any).codeGenType) {
      codeGenType.value = (res.data.data as any).codeGenType as string
    }
    if (res.data.data.initPrompt) {
      input.value = res.data.data.initPrompt
      await send() // 自动发送初始提示词
    }
  }
}

const send = async () => {
  const content = input.value.trim()
  if (!content) return
  sending.value = true
  const userMsg: Msg = { id: Date.now() + '-u', role: 'user', content }
  messages.push(userMsg)
  const aiMsg: Msg = { id: Date.now() + '-a', role: 'ai', content: '' }
  messages.push(aiMsg)
  input.value = ''
  scrollToBottom()
  
  // 获取AI消息在数组中的索引，用于直接更新
  const aiMsgIndex = messages.length - 1
  
  try {
    const url = `/app/chat/gen/code?appId=${appId}&message=${encodeURIComponent(content)}`
    const es = new EventSource(`http://localhost:8125/api${url}`, { withCredentials: true } as any)
    
    es.onmessage = (e) => {
      let chunk = e.data
      console.log('收到数据块:', chunk)
      
      try {
        const obj = JSON.parse(e.data)
        if (obj && Object.prototype.hasOwnProperty.call(obj, 'd')) {
          chunk = obj.d
        }
      } catch (_) {
        // 非 JSON，保持原样
      }
      
      if (chunk === '[DONE]' || chunk === 'DONE') {
        console.log('数据流结束')
        es.close()
        previewUrl.value = `http://localhost:8125/api/static/${codeGenType.value}_${appId}/`
        sending.value = false
        return
      }
      
      // 直接通过索引更新数组中的消息内容，确保Vue响应式系统能检测到变化
      const newContent = String(chunk ?? '')
      messages[aiMsgIndex].content += newContent
      console.log('更新消息内容，当前长度:', messages[aiMsgIndex].content.length)
      scrollToBottom()
    }
    
    es.onerror = () => {
      es.close()
      sending.value = false
    }
    
    es.onopen = () => {
      console.log('EventSource连接已建立')
    }
  } catch (e) {
    console.error('对话失败:', e)
    message.error('对话失败')
    sending.value = false
  }
}

const codeGenType = ref('html')

const doDeploy = async () => {
  deploying.value = true
  try {
    const res = await deployApp({ appId: appId as any })
    if (res.data.code === 0 && res.data.data) {
      previewUrl.value = res.data.data
      deployUrl.value = res.data.data
      deployModalVisible.value = true
    } else {
      message.error('部署失败：' + res.data.message)
    }
  } finally {
    deploying.value = false
  }
}

const goPreview = () => { if(previewUrl.value) window.open(previewUrl.value, '_blank') }

const copyDeployUrl = async () => {
  try {
    await navigator.clipboard.writeText(deployUrl.value)
    message.success('链接已复制到剪贴板')
  } catch (err) {
    message.error('复制失败')
  }
}

const visitDeployUrl = () => {
  window.open(deployUrl.value, '_blank')
  deployModalVisible.value = false
}

onMounted(init)
</script>

<style scoped>
.topbar{ display:flex; align-items:center; justify-content:space-between; padding:8px 0; }
.left{ font-weight:600; font-size:16px }
.core{ display:flex; gap:16px; min-height:60vh }
.chat{ flex:1; display:flex; flex-direction:column; border:1px solid #f0f0f0; border-radius:8px; overflow:hidden }
.messages{ flex:1; padding:12px; overflow:auto; background:#fafafa }
.msg{ margin-bottom:10px; display:flex }
.msg.user{ justify-content:flex-end }
.bubble{ max-width:70%; padding:8px 12px; background:#fff; border-radius:10px; box-shadow:0 1px 2px rgba(0,0,0,.06) }
.msg.user .bubble{ background:#1677ff; color:#fff }
.input{ border-top:1px solid #f0f0f0; padding:8px; background:#fff }
.input-actions{ display:flex; justify-content:flex-end; margin-top:8px }

/* Markdown 内容样式 */
.markdown-content {
  line-height: 1.6;
  word-wrap: break-word;
}

.markdown-content h1,
.markdown-content h2,
.markdown-content h3,
.markdown-content h4,
.markdown-content h5,
.markdown-content h6 {
  margin: 16px 0 8px 0;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-content h1 { font-size: 1.5em; }
.markdown-content h2 { font-size: 1.3em; }
.markdown-content h3 { font-size: 1.1em; }

.markdown-content p {
  margin: 8px 0;
}

.markdown-content ul,
.markdown-content ol {
  margin: 8px 0;
  padding-left: 24px;
}

.markdown-content li {
  margin: 4px 0;
}

.markdown-content blockquote {
  margin: 8px 0;
  padding: 8px 16px;
  border-left: 4px solid #d0d7de;
  background: #f6f8fa;
  color: #656d76;
}

.markdown-content code {
  padding: 2px 6px;
  background: #f6f8fa;
  border-radius: 4px;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 0.9em;
}

.markdown-content pre {
  margin: 12px 0;
  padding: 16px;
  background: #f8f9fa !important;
  border-radius: 8px;
  overflow-x: auto;
  border: 1px solid #e9ecef;
  color: #212529;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.markdown-content pre code {
  padding: 0;
  background: transparent !important;
  border-radius: 0;
  font-size: 0.9em;
  line-height: 1.45;
  color: inherit;
  white-space: pre-wrap;
  word-wrap: break-word;
  display: block;
}

/* 确保 highlight.js 的语法高亮样式能够正确显示 - 浅色主题 */
.markdown-content pre code.hljs {
  background: transparent !important;
  color: #212529;
}

.markdown-content pre code .hljs-comment,
.markdown-content pre code .hljs-quote {
  color: #6a737d;
  font-style: italic;
}

.markdown-content pre code .hljs-keyword,
.markdown-content pre code .hljs-selector-tag,
.markdown-content pre code .hljs-type {
  color: #d73a49;
  font-weight: bold;
}

.markdown-content pre code .hljs-string,
.markdown-content pre code .hljs-doctag {
  color: #032f62;
}

.markdown-content pre code .hljs-title,
.markdown-content pre code .hljs-section,
.markdown-content pre code .hljs-selector-id {
  color: #6f42c1;
}

.markdown-content pre code .hljs-attribute,
.markdown-content pre code .hljs-attr,
.markdown-content pre code .hljs-variable,
.markdown-content pre code .hljs-template-variable,
.markdown-content pre code .hljs-class .hljs-title {
  color: #e36209;
}

.markdown-content pre code .hljs-number,
.markdown-content pre code .hljs-literal {
  color: #005cc5;
}

.markdown-content pre code .hljs-tag,
.markdown-content pre code .hljs-name,
.markdown-content pre code .hljs-selector-class,
.markdown-content pre code .hljs-selector-attr,
.markdown-content pre code .hljs-selector-pseudo {
  color: #22863a;
}

.markdown-content pre code .hljs-built_in,
.markdown-content pre code .hljs-builtin-name {
  color: #005cc5;
}

.markdown-content pre code .hljs-meta {
  color: #6a737d;
}

.markdown-content pre code .hljs-function {
  color: #6f42c1;
}

.markdown-content pre code .hljs-params {
  color: #e36209;
}

.markdown-content pre code .hljs-property {
  color: #e36209;
}

.markdown-content pre code .hljs-deletion {
  background: #ffeef0;
  color: #d73a49;
}

.markdown-content pre code .hljs-addition {
  background: #f0fff4;
  color: #22863a;
}

.markdown-content table {
  border-collapse: collapse;
  margin: 12px 0;
  width: 100%;
}

.markdown-content th,
.markdown-content td {
  padding: 8px 12px;
  border: 1px solid #d0d7de;
  text-align: left;
}

.markdown-content th {
  background: #f6f8fa;
  font-weight: 600;
}

.markdown-content a {
  color: #0969da;
  text-decoration: none;
}

.markdown-content a:hover {
  text-decoration: underline;
}

.markdown-content strong {
  font-weight: 600;
}

.markdown-content em {
  font-style: italic;
}

/* 用户消息中的 Markdown 样式调整 */
.msg.user .markdown-content {
  color: #fff;
}

.msg.user .markdown-content code {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
}

.msg.user .markdown-content pre {
  background: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.3);
}

.msg.user .markdown-content pre code {
  background: transparent;
  color: #fff;
}

.msg.user .markdown-content blockquote {
  background: rgba(255, 255, 255, 0.1);
  border-left-color: rgba(255, 255, 255, 0.5);
  color: rgba(255, 255, 255, 0.9);
}

.msg.user .markdown-content a {
  color: #fff;
  text-decoration: underline;
}
.preview{ flex:1; border:1px dashed #d9d9d9; border-radius:8px; min-height:480px; display:flex; align-items:stretch }
.placeholder{ margin:auto; color:#94a3b8 }
.frame{ width:100%; border:0; border-radius:8px }

/* 部署成功弹窗样式 */
.deploy-success {
  text-align: center;
  padding: 20px 0;
}

.success-icon {
  margin-bottom: 16px;
}

.success-title {
  font-size: 20px;
  font-weight: 600;
  color: #262626;
  margin-bottom: 8px;
}

.success-desc {
  color: #8c8c8c;
  margin-bottom: 24px;
  line-height: 1.5;
}

.url-container {
  display: flex;
  margin-bottom: 24px;
  gap: 8px;
}

.url-input {
  flex: 1;
}

.copy-btn {
  flex-shrink: 0;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.visit-btn {
  min-width: 100px;
}
</style>


